package scm.rawMaterialPurchasing.session;

import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import scm.rawMaterialPurchasing.entity.BOMEntity;
import scm.rawMaterialPurchasing.entity.BOMLineItemEntity;
import scm.rawMaterialPurchasing.entity.RawMaterialEntity;

@Stateless
@LocalBean
public class BOMSessionBean {

    @PersistenceContext
    private EntityManager em;

    public void remove(Long bomId) {

        System.out.println("here?");
        BOMEntity bom = em.find(BOMEntity.class, bomId);
        System.out.println("here2?");
        System.out.println("flag" + bom.getBomLineItems().size());
        for (int i = 0; i < bom.getBomLineItems().size(); i++) {
            System.out.println("here3?");
            BOMLineItemEntity lineItem = em.find(BOMLineItemEntity.class, bom.getBomLineItems().get(i).getId());
            System.out.println("here4?");
            lineItem.setBillOfMaterials(null);
            em.remove(lineItem);
            System.out.println("which? " + bom.getBomLineItems().get(i));
            System.out.println("removed!!!!!!!!!!!!");

            //em.flush();

        }
                
        bom.getBomLineItems().clear();
        em.flush();
    }

    public void save(List<BOMLineItemEntity> bomLineItemList,Long bomId) {
        BOMEntity bom = em.find(BOMEntity.class, bomId);
        
        for (int i = 0; i < bomLineItemList.size(); i++) {
            bomLineItemList.get(i).setBillOfMaterials(bom);
            em.persist(bomLineItemList.get(i));
            bom.getBomLineItems().add(bomLineItemList.get(i));
          // ;
        }
        //BOMEntity bomtemp = em.find(BOMEntity.class, bomLineItemList.get(0).getBillOfMaterials().getId());
        //em.merge(bomtemp);
        
        em.merge(bom);
        em.flush();

    }
    
    public BOMEntity getBOMbyId(Long i){
         return  em.find(BOMEntity.class, i);
//        Query query = em.createQuery("SELECT r FROM RBOMEntity r WHERE r.id = :id ");
//        query.setParameter("id", i);
//        return (BOMEntity) query.getSingleResult();
    }

    public List<String> getAllRawMaterialNames() {
        Query query = em.createQuery("SELECT r.rawMaterialName FROM RawMaterialEntity r");
        return query.getResultList();
    }

    public RawMaterialEntity getRawMaterialByName(String name) {

        Query query = em.createQuery("SELECT r FROM RawMaterialEntity r WHERE r.rawMaterialName = :name ");
        query.setParameter("name", name);
        return (RawMaterialEntity) query.getSingleResult();

    }
    
    public RawMaterialEntity getRawMaterialById(Long id){
        
        return em.find(RawMaterialEntity.class, id);
    }
}
